package com.example.demo.WebSocket;
import com.example.demo.Info.*;
import com.example.demo.Mapper.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Random;

@Component
public class Game_Room_Socket extends TextWebSocketHandler {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private Websocket_And_Room_Manage websocket_and_room_manage;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        user_info userInfo=(user_info) session.getAttributes().get("user");
//        判读是否多开
        if (websocket_and_room_manage.game_room_websocket.get(userInfo.getUserid())==null){
            websocket_and_room_manage.game_room_websocket.put(userInfo.getUserid(),session);
        }else{
//            将多开反馈
            Game_Hall_Websocket_Response gameHallWebsocketResponse=new Game_Hall_Websocket_Response();
            gameHallWebsocketResponse.setMessage("repeatConnection");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(gameHallWebsocketResponse)));
        }
//        获取游戏房间
        Room room=websocket_and_room_manage.room_manage.get(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
        synchronized (room){
            if (room.getUserInfo1()==null){
                room.setRoom_id(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
                room.setUserInfo1(userInfo);
            }else {
//                随机分配先手机会
                room.setUserInfo2(userInfo);
                Random random=new Random();
                int white_userid_random=random.nextInt(100)+1;
                if (white_userid_random%2==0){
                    room.setWhite_userid(room.getUserInfo1().getUserid());
                }else {
                    room.setWhite_userid(room.getUserInfo2().getUserid());
                }
                ui_initial(room.getRoom_id(),room.getUserInfo1().getUserid(),room.getUserInfo2().getUserid(),room.getWhite_userid());
                ui_initial(room.getRoom_id(),room.getUserInfo2().getUserid(),room.getUserInfo1().getUserid(),room.getWhite_userid());
            }
        }
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        user_info userInfo=(user_info) session.getAttributes().get("user");
        Room room=websocket_and_room_manage.room_manage.get(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
        String payload=message.getPayload();
        Game_Room_Websocket_Request gameRoomWebsocketRequest=objectMapper.readValue(payload,Game_Room_Websocket_Request.class);
        if (gameRoomWebsocketRequest.getMessage().equals("putChess")){
            room.putchess(gameRoomWebsocketRequest.getUserId(),gameRoomWebsocketRequest.getRow(),gameRoomWebsocketRequest.getCol());
        }
        switch (userInfo.getScore()/100){
            case 0:userInfo.setTier("学士");break;
            case 1:userInfo.setTier("士人");break;
            case 2:userInfo.setTier("专家");break;
            case 3:userInfo.setTier("大师预备");break;
            case 5:userInfo.setTier("大师");break;
            case 6:userInfo.setTier("宗师-小有成就");break;
            case 8:userInfo.setTier("宗师-卓越大师");break;
            case 10:userInfo.setTier("宗师-巅峰宗师");break;
        }
        if (userInfo.getScore()/100>10){
            userInfo.setTier("宗师-巅峰宗师-"+userInfo.getScore()/1000+"重天");
        }
        if (gameRoomWebsocketRequest.getMessage().equals("winner")){
            if(userInfo.getScore()>=1000){
                userInfo.setScore(userInfo.getScore()+20);
            }else {
                userInfo.setScore(userInfo.getScore()+10);
            }
            userInfo.setWin_count(userInfo.getWin_count()+1);
            userInfo.setGame_count(userInfo.getGame_count()+1);
            userMapper.update_score(userInfo);
//          胜负已定，游戏结束，销毁房间
            websocket_and_room_manage.room_manage.remove(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
            websocket_and_room_manage.room_user_manage.remove(userInfo.getUserid());
        } else if (gameRoomWebsocketRequest.getMessage().equals("loser")){
            if (userInfo.getScore()-7>=0) {
                if (userInfo.getScore()>=1000){
                    userInfo.setScore(userInfo.getScore()-15);
                }else {
                    userInfo.setScore(userInfo.getScore() - 7);
                }
            }else {
                userInfo.setScore(0);
            }
            userInfo.setGame_count(userInfo.getGame_count()+1);
            userMapper.update_score(userInfo);
//          胜负已定，游戏结束，销毁房间
            websocket_and_room_manage.room_manage.remove(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
            websocket_and_room_manage.room_user_manage.remove(userInfo.getUserid());
        }
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        Game_Room_Websocket_Response gameRoomWebsocketResponse=new Game_Room_Websocket_Response();
        user_info userInfo=(user_info)session.getAttributes().get("user");
        //        中途退场，自动判负
        Room room=websocket_and_room_manage.room_manage.get(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
        if (room!=null){
            gameRoomWebsocketResponse.setMessage("run_away");
            gameRoomWebsocketResponse.setThis_userid(userInfo.getUserid());
            WebSocketSession session1=websocket_and_room_manage.game_room_websocket.get(room.getUserInfo1().getUserid()==userInfo.getUserid()?room.getUserInfo2().getUserid():room.getUserInfo1().getUserid());
            session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(gameRoomWebsocketResponse)));
//            异常离线者自动判负，不扣除负者积分之外的惩罚分
            if (userInfo.getScore()-7>=0) {
                if (userInfo.getScore()>=1000){
                    userInfo.setScore(userInfo.getScore()-15);
                }else {
                    userInfo.setScore(userInfo.getScore() - 7);
                }
            }else {
                userInfo.setScore(0);
            }
            userInfo.setGame_count(userInfo.getGame_count()+1);
            userMapper.update_score(userInfo);
//          胜负已定，游戏结束，销毁房间
            websocket_and_room_manage.room_manage.remove(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
            websocket_and_room_manage.room_user_manage.remove(userInfo.getUserid());
        }
//        删除无效信息
        if (websocket_and_room_manage.game_room_websocket.get(userInfo.getUserid())!=null) {
            websocket_and_room_manage.game_room_websocket.remove(userInfo.getUserid());
            websocket_and_room_manage.room_manage.remove(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
            websocket_and_room_manage.room_user_manage.remove(userInfo.getUserid());
        }
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Game_Room_Websocket_Response gameRoomWebsocketResponse=new Game_Room_Websocket_Response();
        user_info userInfo=(user_info)session.getAttributes().get("user");
        Room room=websocket_and_room_manage.room_manage.get(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
//        中途退场，自动判负
        if (room!=null){
            gameRoomWebsocketResponse.setMessage("run_away");
            gameRoomWebsocketResponse.setThis_userid(userInfo.getUserid());
            WebSocketSession session1=websocket_and_room_manage.game_room_websocket.get(room.getUserInfo1().getUserid()==userInfo.getUserid()?room.getUserInfo2().getUserid():room.getUserInfo1().getUserid());
            session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(gameRoomWebsocketResponse)));
//            逃跑者自动判负，并扣除负者积分和额外三分惩罚积分以作惩罚
            if (userInfo.getScore()-10>=0) {
                if (userInfo.getScore()>=1000){
                    userInfo.setScore(userInfo.getScore()-20);
                }else {
                    userInfo.setScore(userInfo.getScore() - 10);
                }
            }else {
                userInfo.setScore(0);
            }
            userInfo.setGame_count(userInfo.getGame_count()+1);
            userMapper.update_score(userInfo);
//          胜负已定，游戏结束，销毁房间
            websocket_and_room_manage.room_manage.remove(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
            websocket_and_room_manage.room_user_manage.remove(userInfo.getUserid());
        }
//        删除无效信息
        if (websocket_and_room_manage.game_room_websocket.get(userInfo.getUserid())!=null) {
            websocket_and_room_manage.game_room_websocket.remove(userInfo.getUserid());
            websocket_and_room_manage.room_manage.remove(websocket_and_room_manage.room_user_manage.get(userInfo.getUserid()));
            websocket_and_room_manage.room_user_manage.remove(userInfo.getUserid());
        }
    }
    public void ui_initial(String room_id,int this_userid,int that_userid,int white_userid) throws IOException {
//        向前端发送就绪响应，初始化棋盘
        Game_Room_Websocket_Response gameRoomWebsocketResponse=new Game_Room_Websocket_Response();
        gameRoomWebsocketResponse.setRoom_id(room_id);
        gameRoomWebsocketResponse.setThis_userid(this_userid);
        gameRoomWebsocketResponse.setThat_userid(that_userid);
        gameRoomWebsocketResponse.setWhite_userid(websocket_and_room_manage.room_manage.get(room_id).getWhite_userid());
        gameRoomWebsocketResponse.setMessage("gameReady");
        WebSocketSession session=websocket_and_room_manage.game_room_websocket.get(this_userid);
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(gameRoomWebsocketResponse)));
    }
}
